<template>
  <div class="sub-filter">
    <div class="item">
      <div class="head">品牌:</div>
      <div class="body">
        <a href="javascript:;" @click="setBrandId(i.id)" v-for="i in CateGory.brands" :key="i.id">{{i.name}}</a>
      </div>
    </div>
    <div class="item" v-for="item in CateGory.saleProperties" :key="item.id">
      <div class="head">{{item.name}}:</div>
      <div class="body">
        <a href="javascript:;" @click="changeAttrs(item,i)" v-for="i in item.properties" :key="i.id">{{i.name}}</a>
      </div>
    </div>
  </div>
</template>
<script>
import { findSubCategoryFilter } from '@/api/category'
import { onMounted, ref, inject } from 'vue'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
export default {
  name: 'SubFilter',
  setup () {
    const CateGory = ref({})
    const route = useRoute()
    async function getCateGory () {
      const res = await findSubCategoryFilter(route.params.id)
      const result = res.data.result
      result.brands.unshift({
        id: null,
        name: '全部'
      })
      result.saleProperties.forEach(item => {
        item.properties.unshift({
          id: null,
          name: '全部'
        })
      })
      CateGory.value = result
    }
    onMounted(() => {
      getCateGory()
    })
    onBeforeRouteUpdate(() => {
      getCateGory()
    })
    // 引入setBrandId这个顶层组件提供的方法,直接return出去在a标签中使用
    const setBrandId = inject('setBrandId')
    // 引入setAttrs这个顶层组件修改商品属性的方法
    const setAttrs = inject('setAttrs')
    function changeAttrs (item, i) {
      setAttrs([{
        propertyName: item.name,
        groupName: i.name,
        groupId: i.id
      }])
    }
    return {
      CateGory,
      setBrandId,
      changeAttrs
    }
  }
}
</script>
<style scoped lang='less'>
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    padding: 10px 0;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
